﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ElectronicsMarket.Service.IService;
using ElectronicsMarket.Service.Models;

namespace ElectronicsMarket.Service.ServiceImpl
{
    public class OrdersImpl: IOrderService
    {
        private ElectronicsMarketDBClassesDataContext eMEntity;

        public OrdersImpl()
        {
            eMEntity = new ElectronicsMarketDBClassesDataContext();
        }

        public bool createNewOrder(int customerId, long orderId)
        {
            try
            {
                ORDER order = new ORDER();
                order.ORDERS_ID = orderId;
                order.ORDERS_CREATED_AT = DateTime.Now;
                order.IS_PAYED = false;
                order.IS_SHIPPED = false;
                order.ORDERS_CUSTOMER_ID = customerId;
                eMEntity.ORDERs.InsertOnSubmit(order);
                eMEntity.SubmitChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public List<ORDER> getAllOrder()
        {
            List<ORDER> lstorder = eMEntity.ORDERs.ToList();
            return lstorder;
        }

        public void updateOrder(ORDER order)
        {
           ORDER or = eMEntity.ORDERs.Single(o => o.ORDERS_ID == order.ORDERS_ID);
           or.IS_PAYED = true;
           eMEntity.SubmitChanges();
        }

        public long getLastOrderId()
        {
            if (eMEntity.ORDERs.ToList().Count == 0)
                return 0;
            else
            {
                return eMEntity.ORDERs.OrderByDescending(o => o.ORDERS_ID).Select(o => o).First().ORDERS_ID;
            }
        }
    }
}